package com.lucy.property.service.impl;

import cn.hutool.core.lang.Validator;
import com.lucy.common.constant.HttpStatus;
import com.lucy.common.domain.PageResultDTO;
import com.lucy.common.exception.BusinessException;
import com.lucy.property.dao.PropertyBuildingDAO;
import com.lucy.property.dao.PropertyUnitDAO;
import com.lucy.property.entity.PropertyBuilding;
import com.lucy.property.entity.PropertyUnit;
import com.lucy.property.service.PropertyBuildingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * @author kindear
 */
@Slf4j
@Service
public class PropertyBuildingServiceImpl implements PropertyBuildingService {

    @Autowired
    PropertyBuildingDAO dao;


    @Override
    public PageResultDTO<PropertyBuilding> getAll(Pageable pageable, Example<PropertyBuilding> example) {
        Page<PropertyBuilding> page;

        if(Validator.isEmpty(example)){
            page = dao.findAll(pageable);
        }
        else {
            page = dao.findAll(example,pageable);
        }
        List<PropertyBuilding> list = page.getContent();
        PageResultDTO<PropertyBuilding> pageResultDTO = new PageResultDTO<>();


        //封装分页请求结果
        pageResultDTO.setContent(list);
        pageResultDTO.setSize(page.getSize());
        pageResultDTO.setTotalPages(page.getTotalPages());
        pageResultDTO.setNumber(page.getNumber());
        pageResultDTO.setTotalElements(page.getTotalElements());
        return pageResultDTO;
    }

    @Override
    public List<PropertyBuilding> getExample(Example<PropertyBuilding> example) {
        return dao.findAll(example);
    }

    @Override
    public void deleteOne(String id) {
        Optional<PropertyBuilding> entityOp = dao.findById(id);
        if (!entityOp.isPresent()){
            throw new BusinessException(HttpStatus.NOT_FOUND,"文件不存在");
        }
        PropertyBuilding entity = entityOp.get();

        dao.deleteById(id);
    }

    @Override
    public Optional<PropertyBuilding> getOne(String s) {
        return dao.findById(s);
    }

    @Override
    public PropertyBuilding saveOne(PropertyBuilding o) {
        if (Validator.isNotEmpty(o.getId())){
            throw new BusinessException(HttpStatus.BAD_REQUEST,"ID参数错误");
        }
        return dao.save(o);
    }

    @Override
    public PropertyBuilding updateOne(PropertyBuilding o) {
        if (Validator.isEmpty(o.getId())){
            throw new BusinessException(HttpStatus.BAD_REQUEST,"ID参数错误");
        }
        return dao.save(o);
    }
}
